package com.chen.rabbitmq.one;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @author Y·C
 * @version 1.0.0
 * @ClassName Consumer.java
 * @Description 消费者 接收消息的
 * @createTime 2023年05月07日 22:09:00
 */
public class Consumer {
    //队列的名称
    public static final String QUEUE_NAME = "hello";
    //接收消息
    public static void main(String[] args) throws IOException, TimeoutException {
        //创建链接工厂
        ConnectionFactory factory = new ConnectionFactory();
        //工厂IP连接RabbitMQ的队列
        factory.setHost("114.55.37.219");
        //用户名
        factory.setUsername("guest");
        //密码
        factory.setPassword("guest");
        //创建链接 channel.basicPublish("",QUEUE_NAME,null,message.getBytes());
        Connection connection = factory.newConnection();
        //获取信道
        Channel channel = connection.createChannel();

        //推送的消息如何进行消费的接口回调
        DeliverCallback deliverCallback = (consumerTag,message)->{
            System.out.println(new String(message.getBody()));
        };

//        DeliverCallback deliverCallback = new DeliverCallback() {
//            @Override
//            public void handle(String s, Delivery delivery) throws IOException {
//                System.out.println(new String(delivery.getBody()));
//            }
//        };

        //取消消息回调
        CancelCallback cancelCallback = consumerTag->{
            System.out.println("消息消费被中断");
        };

        /**
         *
         消费者消费消息
         * 1.消费哪个队列
         * 2.消费成功之后是否要自动应答 true 代表自动应答 false 手动应答
         * 3.消费者未成功消费的回调
         */

        channel.basicConsume(QUEUE_NAME,true,deliverCallback,cancelCallback);
    }

}
